package com.lzs.common.utils.wechat;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.Charset;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

public class AESUtil {

	private static final Logger logger = LoggerFactory.getLogger(AESUtil.class);

	private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

	private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding";

	private static final String ALGORITHM = "AES";

	private static final int TAG_LENGTH_BIT = 128;

	public static String encrypt(String encryptKey, String content) {
		try {
			SecretKeySpec secretKeySpec = new SecretKeySpec(encryptKey.getBytes(), ALGORITHM);
			Cipher ecipher = Cipher.getInstance(TRANSFORMATION);
			ecipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
			byte [] en = ecipher.doFinal(content.getBytes(DEFAULT_CHARSET));
			return BytesHexStrTranslate.bytesToHex(en);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return null;
		}
	}

	public static String decrypt(String encryptKey, String content) {
		try {
			SecretKeySpec secretKeySpec = new SecretKeySpec(encryptKey.getBytes(), ALGORITHM);
			Cipher dcipher = Cipher.getInstance(TRANSFORMATION);
			dcipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
			return new String(dcipher.doFinal(BytesHexStrTranslate.toBytes(content)),
					DEFAULT_CHARSET);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return null;
		}
	}

	public static String decryptToString(String associatedData, String nonce, String ciphertext, String aesKey)throws Exception {
		try {
			Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
			SecretKeySpec key = new SecretKeySpec(aesKey.getBytes(), "AES");
			GCMParameterSpec spec = new GCMParameterSpec(TAG_LENGTH_BIT, nonce.getBytes());
			cipher.init(Cipher.DECRYPT_MODE, key, spec);
			cipher.updateAAD(associatedData.getBytes());
			return new String(cipher.doFinal(Base64.getDecoder().decode(ciphertext)), "utf-8");
		} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
			throw new IllegalStateException(e);
		} catch (InvalidKeyException | InvalidAlgorithmParameterException e) {
			throw new IllegalArgumentException(e);
		}
	}

//	public static void main(String[] args) throws Exception {
//
//		String[] message = {"SFK1936000011","SFK1936000012","SFK1936000013","SFK1936000014",
//                "SFK1936000015","SFK1936000016","SFK1936000017","SFK1936000018","SFK1936000019","SFK1936000020"};
//		String password = "SFK2019AESJIAMIM";
//        for (String me: message) {
//            String encrypt = AESUtil.encrypt(password, me);
//            System.out.println(me+"    http://auv.scombo.cn/scan?sn="+encrypt);
//        }
//	}
}
